package com.sky.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.domain.Type;
import com.sky.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @author 尹稳健~
 * @version 1.0
 */
@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @GetMapping("/types")
    public String types(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                        Model model){
        PageHelper.startPage(pageNum,10);
        List<Type> typelist = typeService.getAllType();
        PageInfo<Type> pageInfo = new PageInfo<>(typelist);
        model.addAttribute(pageInfo);
        return "admin/types";
    }

    // 跳转添加页面
    @GetMapping("/types/input")
    public String input(Model model){
        Type type = new Type();
        model.addAttribute("type",type);
        return "admin/types_input";
    }
    // 添加类型
    @PostMapping("/types")
    public String savePost(Type type, RedirectAttributes attributes){
        Type typeByName = typeService.getTypeByName(type.getName());
        if (typeByName != null){
            attributes.addFlashAttribute("message","该分类已经存在！,请重新添加分类");
            return "redirect:/admin/types";
        }else{
            typeService.saveType(type);
            attributes.addFlashAttribute("message","添加成功");
            return "redirect:/admin/types";
        }
    }

    // 跳转更新页面
    @GetMapping("/types/{id}/input")
    public String editType(@PathVariable("id") Long id,Model model){
        Type type = typeService.getType(id);
        model.addAttribute("type",type);
        return "admin/types_input";
    }

    // 更新操作
    @PostMapping("/types/{id}")
    public String editPost(@PathVariable("id") Long id,Type type,
                           RedirectAttributes attributes){
        Type typeByName = typeService.getTypeByName(type.getName());
        if (typeByName!=null){
            attributes.addFlashAttribute("message","该分类已经存在，请重新填写一个！");
        }else{
            typeService.updateType(type);
            attributes.addFlashAttribute("message","更新成功！");
        }
        return "redirect:/admin/types";
    }

    // 删除操作
    @GetMapping("/types/{id}/delete")
    public String deleteType(@PathVariable("id") Long id,RedirectAttributes attributes){
        typeService.deleteType(id);
        attributes.addFlashAttribute("message","删除成功！");
        return "redirect:/admin/types";
    }

}
